package com.kawa.kemanage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kawa.kemanage.entity.dto.CommentDTO;
import com.kawa.kemanage.entity.NewsComments;
import com.kawa.kemanage.exception.BadSqlException;
import com.kawa.kemanage.mapper.NewsCommentsMapper;
import com.kawa.kemanage.service.NewsCommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@Service
public class NewsCommentsServiceImpl implements NewsCommentsService {
    @Autowired
    private NewsCommentsMapper commentsMapper;

    /**
     * 获取评论列表
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @param contentId 文章ID（可选）
     * @return
     */
    @Override
    @Cacheable(value = "comments", key = "'list-' + #pageNo + '-' + #pageSize + '-' + #contentId", unless = "#result == null")
    public PageInfo<NewsComments> getCommentList(Integer pageNo, Integer pageSize, Long contentId) {
        PageHelper.startPage(pageNo, pageSize);
        NewsComments newsComments = new NewsComments();
        newsComments.setContentId(contentId);
        List<NewsComments> comments = null;
        try {
            //获取评论列表
            comments = commentsMapper.getCommentList(newsComments);
            //判断评论列表不为空
            if (comments != null && !comments.isEmpty()) {
                //不为空时才查询对应的子评论
                comments.forEach(comment -> {
                    comment.setChildrenComments(getChildComments(comment).getList());
                });
            }
        }catch (Exception e){
            log.error("获取评论列表失败", e);
        }
        return new PageInfo<>(comments);
    }

    /**
     * 获取子评论，通过传递整个父评论获取父评论id用以查询子评论
     * @param comment
     * @return
     */
    public PageInfo<NewsComments> getChildComments(NewsComments  comment){
        PageHelper.startPage(1, 2);
        PageInfo<NewsComments> comments = null;
        try {
            //获取子评论
            comments = new PageInfo<>(commentsMapper.getChildComments(comment));
        }catch (Exception e){
            log.error("获取子评论失败", e);
        }
        return comments;
    }

    @Override
    @Cacheable(value = "comments", key = "'search-' + #keyword + '-' + #pageNo + '-' + #pageSize", unless = "#result == null")
    public PageInfo<NewsComments> searchComments(String keyword, Integer pageNo, Integer pageSize) {
        if (!StringUtils.hasText(keyword)) {
            return getCommentList(pageNo, pageSize, null);
        }
        PageHelper.startPage(pageNo, pageSize);
        List<NewsComments> comments = commentsMapper.searchComments(keyword);
        return new PageInfo<>(comments);
    }

    @Override
    @Transactional
    @CacheEvict(value = "comments", allEntries = true)
    public boolean addComment(NewsComments comment) {
        if (comment == null || !StringUtils.hasText(comment.getCommentText())) {
            return false;
        }
        return commentsMapper.addComment(comment) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "comments", allEntries = true)
    public boolean deleteComment(Long commentId) {
        try {
            if (commentId == null) {
                return false;
            }
            // 获取所有回复
            List<NewsComments> replies = commentsMapper.getReplies(commentId);
            // 删除所有回复
            for (NewsComments reply : replies) {
                commentsMapper.deleteComment(reply.getCommentId());
            }
            // 删除主评论
            return commentsMapper.deleteComment(commentId) > 0;
        } catch (Exception e) {
            log.error("删除评论失败", e);
            throw new RuntimeException("删除评论失败：" + e.getMessage());
        }
    }

    @Override
    @Cacheable(value = "comments", key = "'detail-' + #commentId", unless = "#result == null")
    public NewsComments getCommentById(Long commentId) {
        if (commentId == null) {
            return null;
        }
        return commentsMapper.getCommentById(commentId);
    }

    @Override
    @Cacheable(value = "comments", key = "'replies-' + #parentCommentId", unless = "#result == null")
    public List<NewsComments> getReplies(Long parentCommentId) {
        if (parentCommentId == null) {
            return List.of();
        }
        return commentsMapper.getReplies(parentCommentId);
    }

    @Override
    @Transactional
    @CacheEvict(value = "comments", allEntries = true)
    public boolean updateLikeCount(Long commentId, int increment) {
        if (commentId == null) {
            return false;
        }
        return commentsMapper.updateLikeCount(commentId, increment) > 0;
    }

    /**
     * 查询评论总数
     *
     * @return
     */
    @Override
    public List<NewsComments> commentCount() {
        return commentsMapper.commentCount();
    }

    @Override
    public List<CommentDTO> getCommentsByAuthorId(Long userId) {
        return commentsMapper.getCommentsByAuthorId(userId);
    }

    @Override
    public boolean readCommentMessage(CommentDTO commentDTO) {
        try{
            commentsMapper.readCommentMessage(commentDTO);
        }catch (Exception e){
           return false;
        }
        return true;
    }

    @Override
    public Integer getCommentNumById(Long contentId) {
        return commentsMapper.getCommentNumById(contentId);
    }


    public List<NewsComments> getBatchUserInfo(List<Long> userIds) {
        // 这里需要调用用户服务获取用户信息
        // 实际实现时需要注入用户服务
        return null;
    }

    public List<NewsComments> getBatchArticleInfo(List<Long> contentIds) {
        // 这里需要调用文章服务获取文章信息
        // 实际实现时需要注入文章服务
        return null;
    }
}
